package avoidDeadLock;

import java.util.ArrayList;
import java.util.List;

public class AllocatorDemo {

    public static void main(String[] args) {
        Allocator allocator = new Allocator();
        Account from = new Account(200);
        Account to = new Account(200);
        // 循环申请分配资源
        while(!allocator.apply(from, to));

        from.transfer(to, 10);

        // 释放资源
        allocator.free(from, to);
    }

    static class Allocator {
        private List<Object> als = new ArrayList<>();

        public synchronized boolean apply(Object from, Object to) {
            if (als.contains(from) || als.contains(to)) {
                return false;
            }
            als.add(from);
            als.add(to);
            return true;
        }

        public synchronized boolean free(Object from, Object to) {
            als.remove(from);
            als.remove(to);
            return true;
        }
    }

    static class Account {
        private long balance;

        public Account(long balance) {
            if (balance < 0) {
                throw new IllegalArgumentException("balance必须非负数");
            }
            this.balance = balance;
        }

        public void transfer(Account target, long amount) {


            if (balance > amount) {
                balance -=  amount;
                target.balance += amount;
            }
        }
    }
}


